
package com.example.demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;

/**
 * 字符串工具类 *
 * 
 * @author ZhangLei
 * @mail lei.zhang@gmail.com
 */
public class StringUtil {

    public static final int FULL_SPACE = 0;// 末行全部是空格
    public static final int NOT_FULL_SPACE = 1;// 末行有文字

    public static char[] c;// c 表示全部的字符
    static final String space_8 = "        ";
    static final String space_4 = "    ";

    /**
     * 字符串工具类 <li>负责将字符串进行切割</li>
     * 
     * @param first 第一个字符
     * @param indexCount 一行的字符数
     * @param numCount 总的行数
     * @param type 最后一行的类型 {@link StringUtil#FULL_SPACE}
     *            {@link StringUtil#NOT_FULL_SPACE}
     * @param endString 最后一行的字符串，主要是方便对数据进行截断，返回后以便进行拼接
     * @return 处理后的字符串
     * @throws Exception 如果指定的类型未知，将会抛出未知的类型异常
     */
    public static String numChar(int first, int indexCount, int numCount, int type,
            String endString) throws Exception {
        if (!(type == FULL_SPACE || type == NOT_FULL_SPACE)) {
            throw new Exception("must support the space type");
        }

        int i1 = 0;
        StringBuffer sc = new StringBuffer();
        int num = 0;
        char[] c1;
        {
            if (c != null) {
                for (int i = 0; i < c.length; i++) {
                    // for begin
                    {

                        // 当前行等于页面最大行的时候返回数据源
                        {
                            if (num == numCount) {
                                c1 = new char[c.length - i];
                                for (int j = 0; j < c1.length; j++) {
                                    c1[j] = c[i + j - 1];

                                }

                                for (int j = 0; j < c1.length - 1; j++) {
                                    c1[j] = c1[j + 1];
                                }
                                c = c1;
                                i1 = 0;
                                sc = sc.delete(sc.length() - 1, sc.length());

                                String resultString = sc.toString();
                                if (resultString.endsWith("\n")) {
                                    return sc.deleteCharAt(sc.length() - 1).toString();
                                } else {
                                    return sc.toString();
                                }
                            }
                        }

                        // 如果出现\n的情况填充空格
                        {
                            if ('\n' == c[i]) {
                                int nu = 0;
                                if (num == 0) {
                                    nu = first - i1;
                                } else {
                                    nu = indexCount - i1;
                                }

                                if (nu > 0) {
                                    while (nu > 0) {
                                        sc.append(" ");
                                        nu--;
                                    }
                                    sc.append("\n");
                                    System.out.println("StringUtil.numChar() 输出换行,当前字符为:" + c[i]);
                                    i1 = 0;
                                    num++;
                                    continue;
                                }

                            }
                        }

                        if (c[i] == '\r') {
                            sc.append(" ");
                        }
                        else {
                            sc.append(c[i]);
                        }

                        // 判断时候中文或是英文字符
                        {
                            if (StringUtil.isChinese(c[i])) {
                                i1 += 2;
                            } else {
                                i1 += 1;
                            }
                        }

                        // 如果页面时首行,为指定的字符数量
                        {
                            if ((i1 == first || i1 == first + 1) && num == 0) {
                                if (i1 == first + 1) {
                                    sc.delete(sc.length() - 1, sc.length());
                                }

                                sc.append("\n");
                                i1 = 0;

                                num++;

                            } else if (i1 == indexCount + 1) {// 如果字符数量超过71个为多出的一个字符，去掉一个字符。
                                i1 = 0;
                                i--;

                                char chars = sc.charAt(sc.length() - 1);

                                if (isChinese(chars)) {// 前一个字符为中文
                                    sc.delete(sc.length() - 1, sc.length()).append(" \n");
                                } else {
                                    sc.delete(sc.length() - 1, sc.length());
                                    sc.append("\n");
                                }

                                num++;

                            } else if (i1 == indexCount) {// 如果字符数量达到70则为一行的计算

                                sc.append("\n");
                                i1 = 0;
                                num++;
                            }
                        }

                        // 如果是尾行，并且字符数量为满70的时候，用空格填充满这一行
                        {

                            if (i1 == 0) {
                                // do nothing
                            } else {

                                if (i == c.length - 1 && i1 < indexCount) {

                                    if (num == 0) {
                                        while (first - i1 > 0) {
                                            sc.append(" ");
                                            i1++;
                                        }
                                    } else {
                                        while (indexCount - i1 > 0) {
                                            sc.append(" ");
                                            i1++;
                                        }
                                    }

                                    sc.append("\n");
                                    i1 = 0;
                                    num++;
                                }

                            }

                        }

                    }// for end

                }

            }
        }

        // 如果当前行未满足页面行数，用空格填充满这些行数
        {
            while (numCount > num) {
                for (int j = 0; j < indexCount + 1; j++) {
                    sc.append(" ");
                }
                sc.append("\n");
                num++;

            }
        }

        c = null;
        i1 = 0;
        // return sc.toString();
        String returnString = sc.deleteCharAt(sc.length() - 1).deleteCharAt(sc.length() - 1)
                .deleteCharAt(sc.length() - 1).toString();
        if (type == NOT_FULL_SPACE && null != endString) {
            char[] endChars = endString.toCharArray();
            int charsLength = 0;

            // 计算长度
            for (int j = 0; j < endChars.length; j++) {
                char c = endChars[j];
                if (isChinese(c)) {
                    charsLength += 2;
                } else {
                    charsLength++;
                }
            }

            // 删除字符，然后拼接新的字符
            StringBuilder builder = new StringBuilder(returnString);
            // builder.delete(builder.length()-1-charsLength,
            // builder.length()-1);
            while (charsLength > 0) {
                builder.deleteCharAt(builder.length() - 1);
                charsLength--;
            }

            return builder.toString();
        } else {
            return returnString;
        }

    }

    static boolean isCnorEn(char c) {
        if ((c >= 0x0391 && c <= 0xFFE5)) {
            return true;
        } else if ((c >= 0x0000 && c <= 0x00FF)) {
            return false;
        }
        return false;
    }

    public static boolean checkChinese(char c1) {
        char[] data = new char[1];
        data[0] = c1;
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");

        Matcher matcher = pattern.matcher(new String(data));
        return matcher.matches();
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    public static String isEmptynull(String str) {
        if ("null".equals(str) || str == null) {
            return "";
        }
        return str.trim();
    }

    /**
     * @param allSpace 总的空格数目
     * @param
     * @return
     */
    public static String getLineWithUnderline(int allSpace, String content) {
        StringBuilder builder = new StringBuilder();
        if (TextUtils.isEmpty(content)) {

            while (allSpace > 0) {
                builder.append(" ");
                allSpace--;
            }
            return builder.toString();
        }

        int charsCount = 0;
        char[] dats = content.toCharArray();
        for (int i = 0; i < dats.length; i++) {
            char c = dats[i];
            if (isChinese(c)) {
                charsCount += 2;
            } else {
                charsCount++;
            }
        }

        int spaceCount = allSpace - charsCount;
        builder.append(content);
        while (spaceCount > 0) {
            builder.append(" ");
            spaceCount--;
        }

        return builder.toString();
    }

    public static String ParsebyteString(String str, int numbyte, boolean iscenter) {
        String str1 = isEmptynull(str);
        byte[] by = str1.getBytes();
        int count = numbyte - by.length;
        String str2 = str1;
        while (count > 0) {
            if (iscenter) {
                if (count % 2 == 0) {
                    str2 = " " + str2;
                } else {
                    str2 += " ";
                }
            } else {
                str2 += " ";
            }
            count--;
        }
        return str2;
    }

    // 完整的判断中文汉字和符号
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    // 只能判断部分CJK字符（CJK统一汉字）
    public static boolean isChineseByREG(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");
        return pattern.matcher(str.trim()).find();
    }

    // 只能判断部分CJK字符（CJK统一汉字）
    public static boolean isChineseByName(String str) {
        if (str == null) {
            return false;
        }
        // 大小写不同：\\p 表示包含，\\P 表示不包含
        // \\p{Cn} 的意思为 Unicode 中未被定义字符的编码，\\P{Cn} 就表示 Unicode中已经被定义字符的编码
        String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}";
        Pattern pattern = Pattern.compile(reg);
        return pattern.matcher(str.trim()).find();
    }

    /**
     * <pre>
     * 使文书的内容占满一行
     * </pre>
     * 
     * @return
     */
    public static String[] formatString(int oneLineCount, String... args) {
        int contentCount = 0;
        String[] returnArray = new String[args.length];
        /**
         * 计算空格数目
         */
        for (int i = 0; i < args.length; i++) {
            String string = args[i];
            char[] chars = string.toCharArray();
            for (char c : chars) {
                if (isChinese(c))
                    contentCount += 2;
                else
                    contentCount++;
            }
        }

        int spaceCount = oneLineCount - contentCount;
        int wordSpace = spaceCount / args.length;// 每个下划线需要填充的空格数目。
        for (int i = 0; i < args.length; i++) {
            returnArray[i] = args[i];
        }

        while (wordSpace > 0) {
            for (int i = 0; i < returnArray.length; i++) {
                returnArray[i] += " ";
            }
            wordSpace--;
        }
        // 将空格补充到下划线字符的后面,目前只考虑如下情况
        switch (spaceCount % args.length) {
            case 0:
                // do noting
                // returnArray[returnArray.length - 1] += " ";
                break;
            case 1:
                returnArray[0] += " ";
                break;
            case 2:
                returnArray[0] += " ";
                returnArray[1] += " ";
                break;
            case 3:
                returnArray[0] += " ";
                returnArray[1] += " ";
                returnArray[2] += " ";
                break;
            case 4:
                returnArray[0] += " ";
                returnArray[2] += " ";
                returnArray[1] += " ";
                returnArray[3] += " ";
                break;
            case 5:
                returnArray[0] += " ";
                returnArray[1] += " ";
                returnArray[2] += " ";
                returnArray[3] += " ";
                returnArray[4] += " ";
                break;
            case 6:
                returnArray[0] += " ";
                returnArray[1] += " ";
                returnArray[2] += " ";
                returnArray[4] += " ";
                returnArray[3] += " ";
                returnArray[5] += " ";
                break;
            case 7:
                returnArray[0] += " ";
                returnArray[2] += " ";
                returnArray[1] += " ";
                returnArray[3] += " ";
                returnArray[4] += " ";
                returnArray[5] += " ";
                returnArray[6] += " ";
                break;
            default:
                // do nothing
                break;
        }

        return returnArray;
    }
}
